const mongoose = require('mongoose')
// 连接mongodb数据库
mongoose.connect('mongodb://127.0.0.1:27017/bilibili')

// 设置回调
// once 一次 事件回调函数只执行一次
// mongoose.connection.once('open', () => {  //连接成功的回调
//   console.log('连接成功')
// })
mongoose.connection.once('open', async () => {  //连接成功的回调
  console.log('连接成功')

  const catSchema = new mongoose.Schema({
    name:String,
    age:Number,
    color:String
  })

  const Cat = mongoose.model('Cat', catSchema)
  Cat.create({name:'小白',age:2,color:'white'}).then(res=>{
    console.log('创建成功',res)
    mongoose.disconnect()  //断开连接 项目运行中不会添加该代码
  }).catch(err=>{
    console.log('创建失败',err)
  })

})
mongoose.connection.on('error', () => {  //连接失败的回调
  console.log('连接失败')
})
mongoose.connection.on('close', () => {  //连接关闭的回调
  console.log('连接关闭')
})